<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.labeltemplate_add" @click="openPrintLabelModal">新 增 </el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.labeltemplate_delete" @click="handleDelete">删 除 </el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot-scope="{ row, index }" slot="menu">
        <!--        <el-button v-if="permission.labeltemplate_view" icon="el-icon-view" size="small" type="text" @click="rowView(row)">查看</el-button>-->
        <el-button v-if="permission.labeltemplate_edit" icon="el-icon-edit" size="small" type="text" @click.stop="openUpdate(row)">编辑</el-button>
        <el-button v-if="permission.labeltemplate_download" icon="el-icon-download" size="small" type="text" @click.stop="openDownload(row)">下载</el-button>
        <el-button v-if="permission.labeltemplate_delete" icon="el-icon-delete" size="small" type="text" @click="$refs.crud.rowDel(row, index)">删除</el-button>
      </template>
    </avue-crud>
    <el-dialog append-to-body :title="dialogTitle" :visible.sync="printLabelModal" @close="closeDialog" class="labeltemplateDialog">
      <avue-form ref="printLabelForm" v-model="form" v-if="printLabelModal" :option="printLabelOption" :upload-before="uploadBefore" :upload-after="uploadAfter">
        <template slot="code">
          <el-input placeholder="请输入编码" v-model="form.code">
            <el-button slot="append" icon="el-icon-refresh-right" @click="updateCode"></el-button>
          </el-input>
        </template>
        <template slot="clientName">
          <el-input placeholder="请选择 客户/供应商" v-model="form.clientName" class="input-with-select" disabled>
            <el-button
              slot="append"
              icon="el-icon-circle-close"
              v-if="form.clientName"
              @click="
                form.clientName = '';
                form.vendorId = '';
              "
            ></el-button>
            <el-button slot="append" icon="el-icon-search" @click="openPartnerCommonModal"></el-button>
          </el-input>
        </template>
      </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="dialogTitle === '新增'" size="small" type="primary" @click="onSavePrintLabel"><i class="el-icon-circle-plus-outline"></i><span>保 存</span></el-button>
        <el-button v-if="dialogTitle === '编辑'" size="small" type="primary" @click="onSavePrintLabel"><i class="el-icon-circle-check"></i><span>修 改</span></el-button>
        <el-button v-if="dialogTitle !== '查看'" size="small" @click="printLabelModal = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows"></common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from '@/api/admin/labeltemplate';
import { mapGetters } from 'vuex';
import { guid } from '@/util/helpers';
import { downloadFileByUrl } from '@/util/util';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  name: 'AdminLabeltemplate',
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  inject: ['globalStartLoad', 'globalEndLoad'],
  data() {
    return {
      pageCode: 'ADMIN_LABEL_TEMPLATE',
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        menuWidth: 250,
        border: true,
        index: true,
        addBtn: false,
        viewBtn: true,
        viewBtnText: '详情',
        viewTitle: '详情',
        editBtn: false,
        delBtn: false,
        selection: true,
        dialogClickModal: false,
        indexLabel: '序号',
        columnBtn: false,
        column: [
          {
            label: '名称',
            prop: 'fileName',
            search: true
          },
          {
            label: '代码',
            prop: 'code',
            search: true
          },
          {
            label: '版本名称',
            prop: 'revision'
          },
          {
            label: '缩略图',
            prop: 'thumbnailUrl',
            type: 'upload',
            loadText: '缩略图上传中，请稍等',
            propsHttp: {
              url: 'link',
              name: 'originalName',
              res: 'data'
            },
            listType: 'picture',
            limit: 1,
            accept: 'image/png, image/jpeg, image/jpg',
            tip: '只能上传png/jpeg/jpg文件',
            action: '/api/blade-resource/oss/endpoint/put-file-attach'
          },
          {
            label: '标签地址',
            prop: 'fileUrl'
          },
          // {
          //     label: "大小",
          //     prop: "size"
          // },
          // {
          //     label: "资料库名称",
          //     prop: "repoName"
          // },
          {
            label: '类型',
            prop: 'type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=label_template_type'
          },
          {
            label: '打印列数',
            prop: 'columnCount'
          },
          {
            label: '打印份数',
            prop: 'copies'
          },
          {
            label: '客户',
            prop: 'clientName'
          }
        ]
      },
      printLabelModal: false,
      dialogTitle: '新增',
      printLabelOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 125,
        column: [
          {
            label: '名称',
            prop: 'fileName',
            disabled: true
          },
          {
            label: '代码',
            prop: 'code',
            rules: [
              {
                required: true,
                message: '请输入代码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '类型',
            prop: 'type',
            type: 'select',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=label_template_type',
            rules: [
              {
                required: true,
                message: '请选择类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '打印列数',
            prop: 'columnCount',
            type: 'number',
            precision: 0,
            minRows: 1,
            rules: [
              {
                required: true,
                message: '请输入打印列数',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '打印份数',
            prop: 'copies',
            type: 'number',
            precision: 0,
            minRows: 1,
            rules: [
              {
                required: true,
                message: '请输入打印份数',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '客户/供应商',
            prop: 'clientName'
          },
          {
            label: '上传缩略图',
            prop: 'thumbnailUrl',
            type: 'upload',
            loadText: '缩略图上传中，请稍等',
            propsHttp: {
              url: 'link',
              name: 'originalName',
              res: 'data'
            },
            listType: 'picture',
            limit: 1,
            accept: 'image/png, image/jpeg, image/jpg',
            tip: '只能上传png/jpeg/jpg文件',
            action: '/api/blade-resource/oss/endpoint/put-file-attach'
          },
          {
            label: '上传打印标签',
            prop: 'fileUrl',
            type: 'upload',
            loadText: '标签上传中，请稍等',
            propsHttp: {
              url: 'link',
              name: 'originalName',
              res: 'data'
            },
            listType: 'text',
            limit: 1,
            accept: '.btw',
            tip: '只能上传btw文件',
            action: '/api/blade-resource/oss/endpoint/put-file-attach',
            rules: [
              {
                required: true,
                message: '请上传打印标签',
                trigger: 'blur'
              }
            ]
          }
          // {
          //     label: "大小",
          //     prop: "size",
          //     rules: [{
          //         required: true,
          //         message: "请输入 大小",
          //         trigger: "blur"
          //     }]
          // },
          // {
          //     label: "资料库名称",
          //     prop: "repoName",
          //     rules: [{
          //         required: true,
          //         message: "请输入 资料库名称",
          //         trigger: "blur"
          //     }]
          // }
        ]
      },
      data: [],
      tableOption: {} //公用模态框配置信息
    };
  },
  mounted() {
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.labeltemplate_add, false),
        viewBtn: this.vaildData(this.permission.labeltemplate_view, false),
        delBtn: this.vaildData(this.permission.labeltemplate_delete, false),
        editBtn: this.vaildData(this.permission.labeltemplate_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    openPrintLabelModal() {
      this.printLabelModal = true;
      this.dialogTitle = '新增';
      this.form.code = guid().substr(24, 12);
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      // if (['edit', 'view'].includes(type)) {
      //   getDetail(this.form.id).then((res) => {
      //     this.form = res.data.data;
      //   });
      // }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    /**
     * 更新编码
     */
    updateCode() {
      this.form.code = guid().substr(24, 12);
    },
    /**
     * 打开客户信息模态框
     */
    openPartnerCommonModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择客户',
        url: '/api/mes-admin/partner/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '伙伴类型',
            prop: 'partnerType',
            dicUrl: '/api/blade-system/dict/dictionary?code=partner_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: 'erp主键',
            prop: 'erpKey'
          },
          {
            label: '编码',
            prop: 'code',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '缩写',
            prop: 'abbreviation'
          },
          {
            label: '联系人',
            prop: 'principal'
          },
          {
            label: '联系方式',
            prop: 'contacts'
          },
          {
            label: '位置',
            prop: 'locations'
          }
        ]
      };
    },
    /**
     * 选择模态框行数据
     */
    getSelectedRows(rowData) {
      this.form.vendorId = rowData.id;
      this.form.clientName = rowData.name;
    },
    onSavePrintLabel() {
      this.$refs.printLabelForm.validate((valid, done) => {
        if (valid) {
          if (this.dialogTitle === '新增') {
            this.form.thumbnailUrl = this._get(this.form, 'thumbnailUrl[0].value', '');
            this.form.fileUrl = this._get(this.form, 'fileUrl[0].value', '');
            add(this.form).then(
              (res) => {
                this.onLoad(this.page);
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                });
                this.printLabelModal = false;
              },
              (error) => {
                window.console.log(error);
              }
            );
            done();
          } else if (this.dialogTitle === '编辑') {
            this.form.extFields = null;
            update(this.form).then(
              () => {
                this.onLoad(this.page);
                this.$message({
                  type: 'success',
                  message: '编辑成功!'
                });
                this.printLabelModal = false;
              },
              (error) => {
                console.log(error);
              }
            );
            done();
          }
        }
      });
    },
    closeDialog() {
      this.$refs.printLabelForm.resetFields();
      this.form = {};
      // console.log(this.form);
    },
    /**
     * 查看详情数据
     */
    rowView(row) {
      this.printLabelModal = true;
      this.dialogTitle = '查看';
      this.$nextTick(() => {
        this.$refs.printLabelForm.allDisabled = true;
      });
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
      });
    },
    /**
     * 修改物料数据
     */
    openUpdate(row) {
      this.printLabelModal = true;
      this.dialogTitle = '编辑';
      this.$nextTick(() => {
        this.$refs.printLabelForm.allDisabled = false;
      });
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
      });
    },
    // 下载
    openDownload(row) {
      if (row.fileUrl) {
        this.globalStartLoad('文件下载中，请稍后...');
        downloadFileByUrl(row.fileUrl, row.fileName);
        this.globalEndLoad();
      }
    },
    /**
     * 上传前方法
     */
    uploadBefore(file, done, loading, column) {
      if (column.label === '上传打印标签') {
        if (file.name.split('.')[1] != 'btw') {
          this.$message({
            type: 'warning',
            message: '只能上传btw文件！'
          });
          loading();
          return;
        } else {
          done();
        }
      } else {
        if (file.name.split('.')[1] != 'png' && file.name.split('.')[1] != 'jpeg' && file.name.split('.')[1] != 'jpg') {
          this.$message({
            type: 'warning',
            message: '只能上传png/jpeg/jpg文件！'
          });
          loading();
          return;
        } else {
          done();
        }
      }
    },

    /**
     * 上传后方法
     */
    uploadAfter(res, done, loading, column) {
      if (column.prop === 'thumbnailUrl') {
        this.form.thumbnailAttachId = res.attachId;
      } else if (column.prop === 'fileUrl') {
        this.form.labelAttachId = res.attachId;
        this.form.fileName = res.originalName.split('.')[0];
      }
      done();
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__header {
  padding: 16px 24px;
  min-height: 20px;
  border-bottom: 1px solid #f0f0f0;
}
::v-deep .el-dialog__footer {
  border-top: 1px solid #f0f0f0;
  padding: 10px 16px;
}
// ::v-deep .el-dialog {
//   .el-dialog__body {
//     .avue-form__menu {
//       display: none;
//     }
//   }
// }
</style>
